package com.ice.work.moment.oauth.config;

import com.honeybee.cloud.framework.oauth.service.SsoTokenServices;
import com.honeybee.cloud.framework.oauth.config.OauthAuthorizationServerConfig;
import com.ice.work.moment.oauth.service.OauthUserDetailsService;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author DELL
 * @Create 2018-12-13
 * @Since 1.0.0
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends OauthAuthorizationServerConfig {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private HikariDataSource dataSource;

    @Autowired
    private OauthUserDetailsService oauthUserDetailsService;

    @Bean
    JdbcTokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    @Bean
    public JdbcClientDetailsService clientDetails() {
        return new JdbcClientDetailsService(dataSource);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        JdbcClientDetailsService clientDetailsService = clientDetails();
        clients.withClientDetails(clientDetailsService);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore())
                .userDetailsService(oauthUserDetailsService)
                .authenticationManager(authenticationManager);
        endpoints.tokenServices(defaultTokenServices());
        //认证异常翻译
        endpoints.exceptionTranslator(webResponseExceptionTranslator());
    }


    @Override
    @Primary
    @Bean
    public DefaultTokenServices defaultTokenServices() {
        SsoTokenServices tokenServices = new SsoTokenServices();
        tokenServices.setTokenStore(tokenStore());
        tokenServices.setClientDetailsService(clientDetails());
        tokenServices.setSupportRefreshToken(true);
        // 50年？
        tokenServices.setAccessTokenValiditySeconds((int) TimeUnit.MINUTES.toSeconds(4320000));
        return tokenServices;
    }
}
